本文介绍了理解javascript承诺对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在javascript中包围promise对象。所以我在这里有一小段代码。我在promise对象的两边都有一个promise对象和两个console.log()。我认为它会打印

I am trying to wrap my head around promise object in javascript.So here i have this little piece of code.I have a promise object and two console.log() on either side of the promise object.I thought it would print

那里

zami

但它已打印

HI

zami

there

为什么它就像那样。我对如何工作没有任何理解,但我理解异步回调在javascript中是如何工作的。任何人都可以对这个主题有所了解吗?

why it is like that.i have zero understanding on how promise works,but i understand how asynchronous callback works in javascript.Can any one shed some light on this topic?

console.log('hi');
var myPromise = new Promise(function (resolve, reject) {
    if (true) {
        resolve('There!');
    } else {
        reject('Aww, didn\'t work.');
    }
});

myPromise.then(function (result) {
    // Resolve callback.
    console.log(result); 
}, function (result) {
    // Reject callback.
    console.error(result);
});
console.log('zami');


推荐答案

承诺执行是异步的,这意味着它已被执行,但程序不会等到它完成后继续使用其余的代码。

Promise execution is asynchronous, which means that it's executed, but the program won't wait until it's finished to continue with the rest of the code.

基本上,您的代码执行以下操作:

Basically, your code is doing the following:


  1. 记录'嗨'

  2. 创建承诺

  3. 执行承诺

  4. 记录'zami'

  5. 承诺得到解决并记录'那里'。

  1. Log 'Hi'
  2. Create a promise
  3. Execute the promise
  4. Log 'zami'
  5. Promise is resolved and logs 'There'.

如果你想要打印'嗨那里,zami',你必须

If you want it to print 'Hi there, zami', you will have to

myPromise.then(function (result) {
    // Resolve callback.
    console.log(result); 
    console.log('zami');
}, function (result) {
    // Reject callback.
    console.error(result);
});

这篇关于理解javascript承诺对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-23 12:27