I have a command that returns before fulfilling, so I want to wait a little bit before following the promise chain. Is there any best practice to do so?
new Promise(function (resolve, reject) {
exec('netbeast new test-app', function (err, stdout, stderr) {
if (err) return reject(err)
else return resolve(PATH_TO_APP)
})
})
.then(fs.readdirAsync)
.then(fs.readFileAsync.bind(fs, PATH_TO_APP + '/server.js'))
.then(function (data) {
var shebang = data.toString().slice(0, data.toString().indexOf('\n'))
shebang.should.equal('#!/usr/bin/env node')
return Promise.resolve()
})
.then(fs.readJsonAsync.bind(fs, PATH_TO_APP + '/package.json'))
.then(function (data) {
return fs.accessAsync(PATH_TO_APP + '/' + data.main, fs.X_OK)
})
.then(done)
I have a command that returns before fulfilling
If that operation isn't tied to a promise that you can monitor and know when it's done, that sounds like a design mistake. You should fix your operation so it does not fulfill until the async operation is actually done. You don't explain exactly where your problem is with this, but if you did, we could probably help you fix the real problem and not put in a delay hack.
If it's a coordination issue between multiple promises, then you probably just need to make sure the various async operations are appropriately chained together so one waits for the previous, either by returning a promise from within a .then() handler, returning a promise from a function that allows the caller to wait for completion or appropriately chaining the operations with successive .then() handlers.
If you really do need to insert a delay, it looks like you are using Bluebird that contains a built-in delay mechanism. On a given promise p, you can use the .delay(n) method:
p.delay(100).then(...) // wait 100ms before allowing promise chain to proceed
Or, inside a .then() handler, you can return Promise.delay(n) as in:
p.then(function(data) {
...
return Promise.delay(100); // wait 100ms before allowing promise chain to proceed
})
It probably can be useful in some use cases where it is convenient to wait a little bit before starting another action. I think the simplest way would be:
.then(function() {
return new Promise(function (resolve) {
setTimeout(resolve, TIME_TO_WAIT_IN_ms)
})
})
EDIT: I do not think there is a "best practice" for this. Waiting, as commented above, is not contemplated in async programming. However I imagine it can be used in edge cases where, as asked, a workaround is needed.
EDIT 2: As commented below, bluebird (a promise library) has built-in shortcut for this. For a promise p.delay(TIME_IN_ms).then(...) or p.then(() => return Promise.delay(TIME_IN_ms)).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With