var keepsHisWord; keepsHisWord = true; promise1 = newPromise(function(resolve, reject) { if (keepsHisWord) { resolve("The man likes to keep his word"); } else { reject("The man doesnt want to keep his word"); } }); console.log(promise1);
keepsHisWord = false; promise3 = newPromise(function(resolve, reject) { if (keepsHisWord) { resolve("The man likes to keep his word"); } else { reject("The man doesn't want to keep his word"); } }); console.log(promise3);
var momsPromise = newPromise(function(resolve, reject) { momsSavings = 20000; priceOfPhone = 60000; if (momsSavings > priceOfPhone) { resolve({ brand: "iphone", model: "6s" }); } else { reject("We donot have enough savings. Let us save some more money."); } });
momsPromise.then(function(value) { console.log("Hurray I got this phone as a gift ", JSON.stringify(value)); });
momsPromise.catch(function(reason) { console.log("Mom coudn't buy me the phone because ", reason); });
momsPromise.finally(function() { console.log( "Irrespecitve of whether my mom can buy me a phone or not, I still love her" ); });
momsPromise.then( function(value) { console.log("Hurray I got this phone as a gift ", JSON.stringify(value)); }, function(reason) { console.log("Mom coudn't buy me the phone because ", reason); } );
不过从可读性的角度来说,我还是觉得分开写比较好。
为了确保上面所有的例子都能在常见浏览器或 Chrome 中执行,我的代码中没有任何外部依赖。为了加深对主题的理解,我们来创建一个会返回 Promise 的函数,这个 Promise 会被随机的成功执行(resolved)或执行失败(rejected),这样我们就可以在不同的情境下测试我们的代码。为了理解异步函数这一概念,我们的代码中还将加入随机的延迟。既然用到了随机,我们先来创建一个随机返回在 X 和 Y 之间的数值的函数。
1 2 3 4
functiongetRandomNumber(start = 1, end = 10) { //works when both start,end are >=1 and end > start returnparseInt(Math.random() * end) % (end-start+1) + start; }
functiongetRandomNumber(start = 1, end = 10) { //works when both start and end are >=1 return (parseInt(Math.random() * end) % (end - start + 1)) + start; }
var promise3 = Promise.reject("Not interested"); promise3.then(function(value){ console.log("This will not run as it is a resolved promise. The resolved value is ", value); }); promise3.catch(function(reason){ console.log("This run as it is a rejected promise. The reason is ", reason); });
代码 Promise.resolve(value)
帮助你创建一个执行成功(resolved)状态的 Promise。
1 2 3 4 5 6 7
var promise4 = Promise.resolve(1); promise4.then(function(value){ console.log("This will run as it is a resovled promise. The resolved value is ", value); }); promise4.catch(function(reason){ console.log("This will not run as it is a resolved promise", reason); });
顺带说一下,一个 Promise 可以有多个处理函数。所以上面的代码还可以这样写:
1 2 3 4 5 6 7 8 9 10
var promise4 = Promise.resolve(1); promise4.then(function(value){ console.log("This will run as it is a resovled promise. The resolved value is ", value); }); promise4.then(function(value){ console.log("This will also run as multiple handlers can be added. Printing twice the resolved value which is ", value * 2); }); promise4.catch(function(reason){ console.log("This will not run as it is a resolved promise", reason); });
输出结果为:
接下来的两个方法可以帮助你处理多个 Promise。当你要处理多个 Promise 时,最好是先创建一个 Promise 的数组,然后对这个数组采取相应的操作。这次我们不能用 promiseTRRARNOSG 这个函数做例子了,因为它太随机,对与理解我们要说的内容无益。在这里用可以预测其行为的 Promise 比较适合。我们创建两个函数,一个会在 n 秒后执行成功(resolve),另一个会在 n 秒后执行失败(reject)。
console.time("Promise.All"); var promisesArray = []; promisesArray.push(promiseTRSANSG(1)); promisesArray.push(promiseTRSANSG(4)); promisesArray.push(promiseTRSANSG(2)); var handleAllPromises = Promise.all(promisesArray); handleAllPromises.then(function(values) { console.timeEnd("Promise.All"); console.log("All the promises are resolved", values); }); handleAllPromises.catch(function(reason) { console.log("One of the promises failed with the following reason", reason); });
console.time("Promise.All"); var promisesArray = []; promisesArray.push(1); promisesArray.push(4); promisesArray.push(2); var handleAllPromises = Promise.all(promisesArray); handleAllPromises.then(function(values) { console.timeEnd("Promise.All"); console.log("All the promises are resolved", values); }); handleAllPromises.catch(function(reason) { console.log("One of the promises failed with the following reason", reason); });
由于数组中没有 Promise,所以返回的 Promise 是执行成功(resolved)状态。
案例 3:失败信息是数组中第一个执行失败的 Promise 的信息
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
console.time("Promise.All"); var promisesArray = []; promisesArray.push(promiseTRSANSG(1)); promisesArray.push(promiseTRSANSG(5)); promisesArray.push(promiseTRSANSG(3)); promisesArray.push(promiseTRJANSG(2)); promisesArray.push(promiseTRSANSG(4)); var handleAllPromises = Promise.all(promisesArray); handleAllPromises.then(function(values) { console.timeEnd("Promise.All"); console.log("All the promises are resolved", values); }); handleAllPromises.catch(function(reason) { console.timeEnd("Promise.All"); console.log("One of the promises failed with the following reason ", reason); });
var keepsHisWord; keepsHisWord = true; promise1 = newPromise(function(resolve, reject) { if (keepsHisWord) { resolve("The man likes to keep his word"); } else { reject("The man doesnt want to keep his word"); } }); console.log(promise1);
promise2 = newPromise(function(resolve, reject) { setTimeout(function() { resolve({ message: "The man likes to keep his word", code: "aManKeepsHisWord" }); }, 10 * 1000); }); console.log(promise2);
keepsHisWord = false; promise3 = newPromise(function(resolve, reject) { if (keepsHisWord) { resolve("The man likes to keep his word"); } else { reject("The man doesn't want to keep his word"); } }); console.log(promise3);
var momsPromise = newPromise(function(resolve, reject) { momsSavings = 20000; priceOfPhone = 60000; if (momsSavings > priceOfPhone) { resolve({ brand: "iphone", model: "6s" }); } else { reject("We donot have enough savings. Let us save some more money."); } }); momsPromise.then(function(value) { console.log("Hurray I got this phone as a gift ", JSON.stringify(value)); }); momsPromise.catch(function(reason) { console.log("Mom coudn't buy me the phone because ", reason); }); momsPromise.finally(function() { console.log( "Irrespecitve of whether my mom can buy me a phone or not, I still love her" ); });
momsPromise.then( function(value) { console.log("Hurray I got this phone as a gift ", JSON.stringify(value)); }, function(reason) { console.log("Mom coudn't buy me the phone because ", reason); } );
functiongetRandomNumber(start = 1, end = 10) { //works when both start,end are >=1 and end > start returnparseInt(Math.random() * end) % (end-start+1) + start; }
functiongetRandomNumber(start = 1, end = 10) { //works when both start and end are >=1 return (parseInt(Math.random() * end) % (end - start + 1)) + start; } var promiseTRRARNOSG = (promiseThatResolvesRandomlyAfterRandomNumnberOfSecondsGenerator = function() { returnnewPromise(function(resolve, reject) { let randomNumberOfSeconds = getRandomNumber(2, 10); setTimeout(function() { let randomiseResolving = getRandomNumber(1, 10); if (randomiseResolving > 5) { resolve({ randomNumberOfSeconds: randomNumberOfSeconds, randomiseResolving: randomiseResolving }); } else { reject({ randomNumberOfSeconds: randomNumberOfSeconds, randomiseResolving: randomiseResolving }); } }, randomNumberOfSeconds * 1000); }); }); var testProimse = promiseTRRARNOSG(); testProimse.then(function(value) { console.log("Value when promise is resolved : ", value); }); testProimse.catch(function(reason) { console.log("Reason when promise is rejected : ", reason); }); // Let us loop through and create ten different promises using the function to see some variation. Some will be resolved and some will be rejected. for (i=1; i<=10; i++) { let promise = promiseTRRARNOSG(); promise.then(function(value) { console.log("Value when promise is resolved : ", value); }); promise.catch(function(reason) { console.log("Reason when promise is rejected : ", reason); }); }
var promise3 = Promise.reject("Not interested"); promise3.then(function(value){ console.log("This will not run as it is a resolved promise. The resolved value is ", value); }); promise3.catch(function(reason){ console.log("This run as it is a rejected promise. The reason is ", reason); });
var promise4 = Promise.resolve(1); promise4.then(function(value){ console.log("This will run as it is a resovled promise. The resolved value is ", value); }); promise4.catch(function(reason){ console.log("This will not run as it is a resolved promise", reason); });
var promise4 = Promise.resolve(1); promise4.then(function(value){ console.log("This will run as it is a resovled promise. The resolved value is ", value); }); promise4.then(function(value){ console.log("This will also run as multiple handlers can be added. Printing twice the resolved value which is ", value * 2); }); promise4.catch(function(reason){ console.log("This will not run as it is a resolved promise", reason); });
var promiseTRSANSG = (promiseThatResolvesAfterNSecondsGenerator = function( n = 0 ) { returnnewPromise(function(resolve, reject) { setTimeout(function() { resolve({ resolvedAfterNSeconds: n }); }, n * 1000); }); }); var promiseTRJANSG = (promiseThatRejectsAfterNSecondsGenerator = function( n = 0 ) { returnnewPromise(function(resolve, reject) { setTimeout(function() { reject({ rejectedAfterNSeconds: n }); }, n * 1000); }); });
console.time("Promise.All"); var promisesArray = []; promisesArray.push(promiseTRSANSG(1)); promisesArray.push(promiseTRSANSG(4)); promisesArray.push(promiseTRSANSG(2)); var handleAllPromises = Promise.all(promisesArray); handleAllPromises.then(function(values) { console.timeEnd("Promise.All"); console.log("All the promises are resolved", values); }); handleAllPromises.catch(function(reason) { console.log("One of the promises failed with the following reason", reason); });
console.time("Promise.All"); var promisesArray = []; promisesArray.push(1); promisesArray.push(4); promisesArray.push(2); var handleAllPromises = Promise.all(promisesArray); handleAllPromises.then(function(values) { console.timeEnd("Promise.All"); console.log("All the promises are resolved", values); }); handleAllPromises.catch(function(reason) { console.log("One of the promises failed with the following reason", reason); });
console.time("Promise.All"); var promisesArray = []; promisesArray.push(promiseTRSANSG(1)); promisesArray.push(promiseTRSANSG(5)); promisesArray.push(promiseTRSANSG(3)); promisesArray.push(promiseTRJANSG(2)); promisesArray.push(promiseTRSANSG(4)); var handleAllPromises = Promise.all(promisesArray); handleAllPromises.then(function(values) { console.timeEnd("Promise.All"); console.log("All the promises are resolved", values); }); handleAllPromises.catch(function(reason) { console.timeEnd("Promise.All"); console.log("One of the promises failed with the following reason ", reason); });
console.time("Promise.race"); var promisesArray = []; promisesArray.push(promiseTRSANSG(4)); promisesArray.push(promiseTRSANSG(3)); promisesArray.push(promiseTRSANSG(2)); promisesArray.push(promiseTRJANSG(3)); promisesArray.push(promiseTRSANSG(4)); var promisesRace = Promise.race(promisesArray); promisesRace.then(function(values) { console.timeEnd("Promise.race"); console.log("The fasted promise resolved", values); }); promisesRace.catch(function(reason) { console.timeEnd("Promise.race"); console.log("The fastest promise rejected with the following reason ", reason); });
console.time("Promise.race"); var promisesArray = []; promisesArray.push(promiseTRSANSG(4)); promisesArray.push(promiseTRSANSG(6)); promisesArray.push(promiseTRSANSG(5)); promisesArray.push(promiseTRJANSG(3)); promisesArray.push(promiseTRSANSG(4)); var promisesRace = Promise.race(promisesArray); promisesRace.then(function(values) { console.timeEnd("Promise.race"); console.log("The fasted promise resolved", values); }); promisesRace.catch(function(reason) { console.timeEnd("Promise.race"); console.log("The fastest promise rejected with the following reason ", reason); });