我正在尝试链接 Promise。这是代码
crawler.cache(url).then(function (cRes) {
console.log('get from cache');
if(cRes) {
return Promise.resolve(JSON.parse(cRes));
} else {
console.log('no cache');
crawler.db(url).then(function (result) {
console.log('get from db');
return Promise.resolve(JSON.parse(result));
});
}
}).then(function fetch(someResult) {
console.log('fetch data from' + someResult);
});
我希望它能够调查 cache
首先,如果找不到,那么它应该查看 db
。然后将结果传给最后一个then
来获取结果。
但是这是我的控制台打印的内容。
get from cache
no cache
fetch data from null
get from db
首先,它在缓存中找不到任何内容,然后尝试从数据库中获取数据,但它没有等到从数据库中获取数据完成,而是继续访问 fetch data
.
最后then
时我该如何解决这个问题必须等待上面的所有操作完成才能得到结果才能进行下一步操作吗?
最佳答案
您可以在then
延续中返回promise,这将导致父promise等待,直到返回的promise被履行并采用它的值。
也不需要使用Promise.resolve
方法,直接返回值即可。
crawler.cache(url).then(function (cRes) {
if (cRes) {
console.log('cache result');
return JSON.parse(cRes);
} else {
console.log('no cache');
return crawler.db(url).then(function (result) {
return JSON.parse(result);
});
}
}).then(function fetch(someResult) {
console.log('fetch data from' + someResult);
});
奖金:
如果您将缓存存储在内存中。您可能不需要从 crawler.cache
函数返回 promise 。
关于javascript - 如何让后面的 Promise 等待第一个 Promise 在 bluebird 中完成?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34957742/