- 使用 Spring Initializr 创建 Spring Boot 应用程序
- 在Spring Boot中配置Cassandra
- 在 Spring Boot 上配置 Tomcat 连接池
- 将Camel消息路由到嵌入WildFly的Artemis上
在本教程中,您将借助示例了解 JavaScript promise 和 promise 链。
在 JavaScript 中,promise 是处理异步操作的好方法。用于判断异步操作是否成功完成。
promise 可能有以下三种状态之一。
Promise 以待处理状态开始。这意味着该过程尚未完成。如果操作成功,则该过程以已完成状态结束。并且,如果发生错误,则该过程以被拒绝状态结束。
例如,当您使用 Promise 向服务器请求数据时,它将处于待处理状态。当数据成功到达时,它将处于已完成状态。如果发生错误,则它将处于拒绝状态。
要创建一个 Promise 对象,我们使用 Promise() 构造函数。
let promise = new Promise(function(resolve, reject){
//do something
});
Promise() 构造函数将一个函数作为参数。该函数还接收两个函数 resolve() 和 reject() 作为参数。
如果 promise 成功返回,则调用 resolve() 函数。并且,如果发生错误,则调用 reject() 函数。
假设下面的程序是一个异步程序。然后可以使用 promise 来处理该程序。
const count = true;
let countValue = new Promise(function (resolve, reject) {
if (count) {
resolve("There is a count value.");
} else {
reject("There is no count value");
}
});
console.log(countValue);
输出
Promise {<resolved>: "There is a count value."}
上面的程序创建了一个 Promise 对象,它具有两个函数:resolve() 和 reject()。如果程序成功,则使用 resolve();如果 promise 中出现错误,则使用 reject()。
JavaScript promise的工作原理
当您必须一个接一个地处理多个异步任务时,Promise 很有用。为此,我们使用 promise 链。
当 promise 被解析后,您可以使用 then(),catch() 和 finally() 方法执行某个操作。
当 promise 成功实现或解决时,then() 方法与回调一起使用。
then() 方法的语法是:
promiseObject.then(onFulfilled, onRejected);
// returns a promise
let countValue = new Promise(function (resolve, reject) {
resolve("Promise resolved");
});
// executes when promise is resolved successfully
countValue
.then(function successValue(result) {
console.log(result);
})
.then(function successValue1() {
console.log("You can call multiple functions this way.");
});
输出
Promise resolved
You can call multiple functions this way.
在上述程序中,then() 方法用于将函数链接到 Promise。当 promise 成功解析时调用 then() 方法。
你可以用 Promise 链接多个 then() 方法。
当 promise 被拒绝或发生错误时,catch() 方法与回调一起使用。例如,
// returns a promise
let countValue = new Promise(function (resolve, reject) {
reject('Promise rejected');
});
// executes when promise is resolved successfully
countValue.then(
function successValue(result) {
console.log(result);
},
)
// executes if there is an error
.catch(
function errorValue(result) {
console.log(result);
}
);
输出
Promise rejected
在上面的程序中,promise 被拒绝了。该catch()方法与处理错误的 promise 一起使用。
JavaScript promise 链的工作原理
Promise 在某种意义上类似于回调函数,它们都可以用来处理异步任务。
JavaScript 回调函数也可用于执行同步任务。
它们的区别可以概括为以下几点:
api().then(function(result) {
return api2() ;
}).then(function(result2) {
return api3();
}).then(function(result3) {
// do work
}).catch(function(error) {
//handle any error that may occur before this point
});
api(function(result){
api2(function(result2){
api3(function(result3){
// do work
if(error) {
// do something
}
else {
// do something
}
});
});
});
还可以使用 finally() 方法进行 promise。当 promise 被成功解析或拒绝时,finally() 方法将被执行。例如,
// returns a promise
let countValue = new Promise(function (resolve, reject) {
// could be resolved or rejected
resolve('Promise resolved');
});
// add other blocks of code
countValue.finally(
function greet() {
console.log('This code is executed.');
}
);
输出
This code is executed.
Promise 对象有多种可用的方法。
方法 | 描述 |
---|---|
all(iterable) | 等待所有 Promise 被解析或任何一个被拒绝 |
allSettled(iterable) | 等待所有的 Promise 都被解决或被拒绝 |
any(iterable) | 一旦任何一个 Promise 执行完成,就返回 Promise 值 |
race(iterable) | 等到任何承诺被解析或拒绝 |
reject(reason) | 返回因给定原因被拒绝的新 Promise 对象 |
resolve(value) | 返回使用给定值解析的新 Promise 对象 |
catch() | 追加拒绝处理程序回调 |
then() | 追加已解析的处理程序回调 |
finally() | 在 promise 后附加一个处理程序 |
要详细了解 Promise,请访问使用 Promise。
上一教程 :JS CallBack 下一教程 :JS async/await
[1] Parewa Labs Pvt. Ltd. (2022, January 1). Getting Started With JavaScript, from Parewa Labs Pvt. Ltd: https://www.programiz.com/javascript/promise
如何从 promise 中退出 promise ? perl6 文档没有提供简单的方法。例如: my $x = start { loop { # loop forever until "qui
我的用户 Controller 中有一个索引操作,其中我试图连续做两件事,并且在它们都有机会完成之前不执行所需的 res.json() 方法。 我有一个加入用户的友谊加入模型。一列是 friender
请帮我解释一下为什么日志结果有两种不同: 方式 1:每 1 秒顺序记录一次 方式 2:1 秒后记录所有元素。 // Way 1 let sequence = Promise.resolve(); [1
我的问题很简单。 Promise.all() 方法可以返回 Promise 吗?让我解释一下: function simpleFunction() { let queue = [];
我正在使用 Promise 从存储中读取文件并转换为 base64 字符串。我有图像数组,使用 RNFS 读取图像 const promise_Images = _Images.map(async (
如果使用非空数组调用 Promise.all 或 Promise.race,它们将返回一个待处理的 Promise: console.log(Promise.all([1])); // prints
Promise.all 是否可以在没有包装 promise 的情况下返回链的最后一个值? 如果不使用 await,它在我的上下文中不起作用 没有包装的例子: function sum1(x){ r
我一直在玩 promise,通常能想出如何处理好它们,但在这种情况下,我不知道如何删除一个 promise-wrapping level。 代码如下: let promise2 = promise1.
考虑以下嵌套的Promises结构: const getData = async() => { const refs = [{ name: "John33", age: 3
我已经阅读了 Promise/A+ 规范,但据我了解,还有诸如 Promise/A 和 Promise 之类的东西。它们之间有什么区别? Promise 和 Promise/A 规范也是如此吗?如果是
当我运行以下代码时: my $timer = Promise.in(2); my $after = $timer.then({ say "2 seconds are over!"; 'result'
以下简单的 promise 是发誓的,我不允许打破它。 my $my_promise = start { loop {} # or sleep x; 'promise re
我正在尝试扩展Promise: class PersistedPromise extends Promise { } 然后在派生类上调用静态resolve以直接创建一个已解决的Promise: Per
我有两个返回 promise 的函数,我独立使用它们作为: getLocal().then(...) 和 getWeb().then(...) 但是现在我遇到了一个奇怪的问题: 1) 我需要第三个
我不知道 promise.all 解决方案中的 promise.all 是否是一个好的实践。我不确定。 我需要从一组用户获取信息,然后通过此信息响应,我需要发送消息通知。 let userList =
我一直在尝试使用 queueMicrotask() 函数,但我没有弄清楚当回调是微任务时回调的优先级如何。查看以下代码: function tasksAndMicroTasks() { const
我一直在尝试使用 queueMicrotask() 函数,但我没有弄清楚当回调是微任务时回调的优先级如何。查看以下代码: function tasksAndMicroTasks() { const
今年早些时候,我在 Pharo Smalltalk 参与了一个 promise 项目。这个想法是为了实现以下行为: ([ 30 seconds wait. 4 ]promiseValue )then:
大家好,提前感谢您的帮助。 下面是我正在尝试做的事情 function1(){ throw some error(); } function2() { // dosomething suc
我有以下未解析的代码。f2 解决了,所以我不会添加该代码,它是 f1 我有问题。 我调用函数,它到达最里面如果,它调用函数“find”,它执行函数 findId,完美返回 Id,然后执行 editId
我是一名优秀的程序员,十分优秀!