Last active
July 19, 2018 16:31
-
-
Save akbarsahata/dcd163cee527fcc0fbbbdc713ab19176 to your computer and use it in GitHub Desktop.
Running promises sequentially. Reading and writing data is done asynchronously. There will be a sequence of read write processes, in which each process is determined from the preceding process. If sourceData is written by some process, next process should not write again.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const sourceData = [] | |
const readData = () => new Promise(res => { | |
setTimeout(() => res(sourceData), 500) | |
}) | |
const writeData = (data) => new Promise(res => { | |
setTimeout(() => { | |
sourceData.push(data) | |
res(sourceData) | |
}, 500) | |
}) | |
const querySelect = (query) => new Promise(res => { | |
readData().then(data => res(data)) | |
}) | |
const queryInsert = (data) => new Promise(res => { | |
writeData(data).then(newData => res(newData)) | |
}) | |
function test (array) { | |
const funcs = array.map((v) => () => new Promise(res => { | |
querySelect() | |
.then(data => { | |
if (data && data.length < 1) { | |
queryInsert(v) | |
.then(() => res(true)) | |
} else { | |
res(false) | |
} | |
}) | |
})) | |
return funcs.reduce((promise, func) => | |
promise.then(all => | |
func().then(result => | |
all.concat(result) | |
) | |
) | |
,Promise.resolve([])) | |
} | |
test([1,2,3,4,5]) | |
.then(finalRes => console.log(finalRes)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment