我很难理解javaScript中的链接承诺,所以我决定举一个例子并练习一些代码,这正是我想要做的...
var p = new Promise(function(resolve, request) {
setTimeout(function() {
console.log("Inside heavy task...");
resolve("Heavy task was a success");
}, 5000);
})
.then(function(value) {
setTimeout(function(value) {
console.log("Inside medium task...");
resolve(value);
//reject("Medium task failed !");
}, 3000);
})
.then(function(value) {
console.log("Inside small task...");
console.log("From small task : " + value);
})
.catch( function(reson){
setTimeout(function(reason){
console.log("Inside error task...");
console.log("Failed due to "+reason);
},1000);
});
console.log("Some other tasks...");
据我所知,我的代码的错误可能有人纠正这一点,并解释如何应该这样做。
答案 0 :(得分:0)
首先,如果要将其他参数传递给setTimeout的回调函数,则可以按以下步骤完成
setTimeout(callback, time, param1, param2, ...)
现在在您的代码段中,将第二个setTimeout函数包装在一个promise中并返回该promise。另外,如果您希望小任务异步,则也可以将其包装在一个Promise中并返回该Promise。
var p = new Promise(function(resolve, reject) {
setTimeout(function() {
console.log("Inside heavy task...");
resolve("Heavy task was a success");
}, 5000);
})
.then(function(value) {
var p2 = new Promise(function(resolve, reject) {
setTimeout(function() {
console.log("Inside medium task...");
resolve(value);
// reject("Medium task failed !");
}, 3000);
});
return p2;
})
.then(function(value) {
console.log("Inside small task...");
console.log("From small task : " + value);
})
.catch(function(reason) {
setTimeout(function(){
console.log("Inside error task...");
console.log("Failed due to "+ reason);
}, 1000);
});
console.log("Some other tasks...");
我希望这会有所帮助:)