Promise 链式 vs Promise.all [英] promise chaining vs promise.all

查看:31
本文介绍了Promise 链式 vs Promise.all的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个任务是使用量角器输入通知日期我需要在进入之前清除内容,所以我想出了这个代码

i have a task to enter the notification date using protractor where i need to clear contents before entering so i have came up with this code

 this.Then(/^I should enter "Notification Date"$/, () => {
    const d = new Date();
    return orderCheckOutPage.pageElements.recipientNotificationDateMonth.clear().then(() => {
        return orderCheckOutPage.pageElements.recipientNotificationDateMonth.sendKeys(d.getMonth() + 1).then(() => {
            return orderCheckOutPage.pageElements.recipientNotificationDateDay.clear().then(() => {
                return orderCheckOutPage.pageElements.recipientNotificationDateDay.sendKeys(d.getDate()).then(() => {
                    return orderCheckOutPage.pageElements.recipientNotificationDateYear.clear().then(() => {
                        return orderCheckOutPage.pageElements.recipientNotificationDateYear.sendKeys(d.getFullYear())
                    })
                })
            })
        })
    })
});

我的朋友告诉我上面的代码可以重构为

my friend told me the above code be can refactored as

const 承诺 = [];promises.push(orderCheckOutPage.pageElements.recipientNotificationDateMonth.clear());promises.push(orderCheckOutPage.pageElements.recipientNotificationDateMonth.sendKeys(d.getMonth() + 1));promises.push(orderCheckOutPage.pageElements.recipientNotificationDateDay.clear());promises.push(orderCheckOutPage.pageElements.recipientNotificationDateDay.sendKeys(d.getDate()));promises.push(orderCheckOutPage.pageElements.recipientNotificationDateYear.clear());promises.push(orderCheckOutPage.pageElements.recipientNotificationDateYear.sendKeys(d.getFullYear()));返回 promise.all(promises);

听说promise.all 会开始一一解决promise

I heard promise.all will start resolving promises one by one

首先它会转到第一个语句并尝试解决如果它[在上述情况下是明确的月份]如果是异步的它将跳转到第二个语句并尝试执行语句[将密钥发送到月份]

first it would go to first statement and try to resolve if it [here in the above case is clear month] if is asynch the it would jump to second one and try to execute the statement [sending keys to month]

这里清零和进货都是并行的

here both the tasks of clearing and entering will be run parallely

任务是根据承诺得到解决的时间来执行的

and tasks are executed based on the time promises get resolved

如果是这种情况,sendkeys 是否有机会在清除之前被执行

if it is that case will there be chances of sendkeys being exeuted before clearing

如果我错了请纠正我......!!!!!

correct me if i am wrong...!!!!!

推荐答案

Protractor 有自己的promise 管理机制,叫做控制流,简单理解控制流,你可以认为它是一个队列.

Protractor has its own promise manage mechanism called control flow, To understand control flow simply, you can think it is a queue.

当 nodejs 逐行执行你的 Protractor 脚本时,如果该行中的表达式返回一个 Promise,控制流会将 Promise 添加到队列中.

When nodejs execute your Protractor script line by line, if the expression in the line return a promise, control flow will add the promise into the queue.

所有行执行完成后,你会得到一个promise队列,此时你的测试还没有完成,因为控制流会让你的测试等待队列中的所有promise被执行.现在控制流将从队列中弹出一个promise并执行并等待它完成,然后是下一个promise.

After all lines execute done, you will get a promise queue, at this time point your testing had not finish yet, because control flow will make your testing to wait all promise in the queue be executed. Now control flow will pop a promise from the queue and execute and wait it complete, then next promise.

所以有了这样的机制,你的脚本可以按照你写的顺序执行在文件中.实际上控制流所做的事情比我这里说的要复杂.

So with such mechanism, your script can be executed as the order as you write down in file. Actually what control flow did is more complex than I said here.

在你的情况下你不需要使用嵌套的then链,你的代码就像回调金字塔,不代表promise的优势(promise是解决回调金字塔).您的代码可以简单如下:

You no need to use nested then chain in your case, your code like the callback pyramid, not represent the advantage of promise (promise is to resolve callback pyramid). Your code can be simple as below:

const d = new Date();
//input month
orderCheckOutPage.pageElements.recipientNotificationDateMonth.clear();
orderCheckOutPage.pageElements.recipientNotificationDateMonth.sendKeys(d.getMonth() + 1);
//input day
orderCheckOutPage.pageElements.recipientNotificationDateDay.clear();
orderCheckOutPage.pageElements.recipientNotificationDateDay.sendKeys(d.getDate());
//input year
orderCheckOutPage.pageElements.recipientNotificationDateYear.clear();
orderCheckOutPage.pageElements.recipientNotificationDateYear.sendKeys(d.getFullYear());

对于您的情况,无需使用 promise.all(),因为您的代码的所有交互都不会从页面中获得一些价值.我将举一个例子来帮助您了解在哪种情况下使用 promise.all() 更好:

For your case, no need to use promise.all(), because all interaction of your code not to get some value from page. I will give an example to help you learn in which case it's better to use promise.all():

假设我有一个页面,它显示价格和金额.我需要按价格*金额计算费用.

Assume i have a page and it display a price and a amount. I need to calculate the fee by price * amount.

使用嵌套然后链:

var fee = ele_price.getText().then(function(price){

    return ele_amount.getText().then(function(amount){
        return price * amount;
    });
});

fee.then(function(fee){
    console.log(fee);
});

使用 promise.all():

Use promise.all():

var fee = promise.all([
  ele_price.getText(),
  ele_amount.getText()
])
.then(function(datas){
    var price = datas[0];
    var amount = datas[1];
    return price * amount;
});

fee.then(function(fee){
    console.log(fee);
});

所以使用promise.all(),一个then() 就足够了.这使您的代码比嵌套的 then 链更具可读性.

So use promise.all(), one then() is enough. This makes your code more readable than nested then chain.

希望您现在明白为什么在您的情况下不需要使用 promise.all().

Hope you now understand why no need to use promise.all() in your case.

这篇关于Promise 链式 vs Promise.all的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆