javascript_JavaScript承诺说明

javascript

JavaScript的承诺是什么? (What is a promise in JavaScript?)

JavaScript is single threaded, meaning that two bits of script cannot run at the same time; they have to run one after another. A Promise is an object that represents the eventual completion (or failure) of an asynchronous operation, and its resulting value.

JavaScript是单线程的,这意味着脚本的两个位不能同时运行。 他们必须一个接一个地跑。 Promise是一个对象,代表异步操作的最终完成(或失败)及其结果值。

var promise = new Promise(function(resolve, reject) {
  // do thing, then…

  if (/* everything worked */) {
    resolve("See, it worked!");
  }
  else {
    reject(Error("It broke"));
  }
});

在其中一种状态下存在一个承诺 (A Promise exists in one of these states)

  • Pending: initial state, neither fulfilled nor rejected.

    待定:初始状态,既未实现也不被拒绝。
  • Fulfilled: operation completed successfully.

    已完成:操作成功完成。
  • Rejected: operation failed.

    拒绝:操作失败。

The Promise object works as proxy for a value not necessarily known when the promise is created. It allows you to associate handlers with an asynchronous action’s eventual success value or failure reason.

Promise对象用作创建Promise时不一定已知的值的代理。 它允许您将处理程序与异步操作的最终成功值或失败原因相关联。

This lets asynchronous methods return values like synchronous methods: instead of immediately returning the final value, the asynchronous method returns a promise to supply the value at some point in the future.

这使异步方法像同步方法一样返回值:异步方法返回立即提供最终值的承诺,而不是立即返回最终值。

使用“然后”(承诺链接) (Using ‘Then’ (Promise Chaining))

To take several asynchronous calls and synchronize them one after the other, you can use promise chaining. This allows using a value from the first promise in later subsequent callbacks.

要进行几个异步调用并使其一个接一个地同步,可以使用promise链。 这允许在以后的后续回调中使用来自第一个承诺的值。

Promise.resolve('some')
  .then(function(string) { // <-- This will happen after the above Promise resolves (returning the value 'some')
    return new Promise(function(resolve, reject) {
      setTimeout(function() {
        string += 'thing';
        resolve(string);
      }, 1);
    });
  })
  .then(function(string) { // <-- This will happen after the above .then's new Promise resolves
    console.log(string); // <-- Logs 'something' to the console
  });

Promise API (Promise API)

There are 4 static methods in the Promise class:

Promise类中有4种静态方法:

  • Promise.resolve

    承诺解决
  • Promise.reject

    承诺拒绝
  • Promise.all

    无极
  • Promise.race

    无极种族

承诺可以链接在一起 (Promises can be chained together)

When writing Promises to solve a particular problem, you can chain them together to form logic.

在编写解决特定问题的Promises时,可以将它们链接在一起以形成逻辑。

var add = function(x, y) {
  return new Promise((resolve,reject) => {
    var sum = x + y;
    if (sum) {
      resolve(sum);
    }
    else {
      reject(Error("Could not add the two values!"));
    }
  });
};

var subtract = function(x, y) {
  return new Promise((resolve, reject) => {
    var sum = x - y;
    if (sum) {
      resolve(sum);
    }
    else {
      reject(Error("Could not subtract the two values!"));
    }
  });
};

// Starting promise chain
add(2,2)
  .then((added) => {
    // added = 4
    return subtract(added, 3);
  })
  .then((subtracted) => {
    // subtracted = 1
    return add(subtracted, 5);
  })
  .then((added) => {
    // added = 6
    return added * 2;    
  })
  .then((result) => {
    // result = 12
    console.log("My result is ", result);
  })
  .catch((err) => {
    // If any part of the chain is rejected, print the error message.
    console.log(err);
  });

This is useful for following a Functional Programming paradigm. By creating functions for manipulating data you can chain them together to assemble a final result. If at any point in the chain of functions a value is rejected the chain will skip to the nearest catch() handler.

这对于遵循函数式编程范例很有用。 通过创建用于处理数据的函数,您可以将它们链接在一起以组装最终结果。 如果函数链中的任何点拒绝某个值,则该链将跳至最近的catch()处理函数。

For more information on Functional Programming: Functional Programming

有关函数式编程的更多信息: 函数式编程

函数发生器 (Function Generators)

In recent releases, JavaScript has introduced more ways to natively handle Promises. One such way is the function generator. Function generators are “pausable” functions. When used with Promises, generators can make using a lot easier to read and appear “synchronous”.

在最近的发行版中,JavaScript引入了更多本地处理Promises的方法。 一种这样的方法是函数发生器。 函数发生器是“暂停”函数。 当与Promises一起使用时,生成器可以使使用起来更容易阅读,并且显得“同步”。

const myFirstGenerator = function* () {
  const one = yield 1;
  const two = yield 2;
  const three = yield 3;

  return 'Finished!';
}

const gen = myFirstGenerator();

Here’s our first generator, which you can see by the function* syntax. The gen variable we declared will not run myFirstGenerator, but instead will “this generator is ready to use”.

这是我们的第一个生成器,您可以通过function*语法看到它。 我们声明的gen变量将不会运行myFirstGenerator ,而是将“可以使用此生成器”。

console.log(gen.next());
// Returns { value: 1, done: false }

When we run gen.next() it will unpause the generator and carry on. Since this is the first time we have called gen.next() it will run yield 1 and pause until we call gen.next() again. When yield 1 is called, it will return to us the value that was yielded and whether or not the generator is done.

当我们运行gen.next() ,它将取消暂停生成器并继续运行。 由于这是我们第一次调用gen.next() ,它将运行yield 1并暂停直到再次调用gen.next() 。 调用yield 1 ,它将向我们返回产生的value以及生成器是否done

console.log(gen.next());
// Returns { value: 2, done: false }

console.log(gen.next());
// Returns { value: 3, done: false }

console.log(gen.next());
// Returns { value: 'Finished!', done: true }

console.log(gen.next());
// Will throw an error

As we keep calling gen.next() it will keep going onto the next yield and pausing each time. Once there are no more yield’s left, it will proceed to run the rest of the generator, which in this case simply returns 'Finished!'. If you call gen.next() again, it will throw an error as the generator is finished.

当我们继续调用gen.next() ,它将继续进行下一个yield并每次都暂停。 一旦没有剩余的yield ,它将继续运行生成器的其余部分,在这种情况下,它仅返回'Finished!' 。 如果再次调用gen.next() ,则在生成器完成时它将引发错误。

Now, imagine if each yield in this example was a Promise, the code itself would appear extremely synchronous.

现在,假设如果此示例中的每个yield都是Promise ,则代码本身将看起来非常同步。

Promise.all(iterable)对于对不同来源的多次请求非常有用 (Promise.all(iterable) is very usefull for multiple request to different source)

The Promise.all(iterable) method returns a single Promise that resolves when all of the promises in the iterable argument have resolved or when the iterable argument contains no promises. It rejects with the reason of the first promise that rejects.

Promise.all(iterable)方法返回一个Promise,当可迭代参数中的所有promise已解决或可迭代参数不包含promise时,该Promise进行解析。 它拒绝的原因是第一个承诺被拒绝。

var promise1 = Promise.resolve(catSource);
var promise2 = Promise.resolve(dogSource);
var promise3 = Promise.resolve(cowSource);

Promise.all([promise1, promise2, promise3]).then(function(values) {
  console.log(values);
});
// expected output: Array ["catData", "dogData", "cowData"]

有关承诺的更多信息: (More info on Promises:)

翻译自: https://www.freecodecamp.org/news/javascript-promises-explained/

javascript

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值