简体   繁体   English

在 Promise 链接中出现未定义的错误,如果 then 有多行代码

[英]getting undefined error in Promise Chaining if then has multiple lines of code

Iam doing a vary basic promise demo code.我正在做一个不同的基本 promise 演示代码。 Can anybody please explain me the reason why the followng code block gives undefined?谁能解释一下为什么下面的代码块给出未定义的原因? Any help would be highky appreciated.任何帮助将不胜感激。

This is my promise Definition code.这是我的 promise 定义代码。 I have created three functions each returning a promise.我创建了三个函数,每个函数都返回一个 promise。 For now, iam using setTimeout in the example现在,我在示例中使用 setTimeout

// promise-definitions.js // 承诺定义.js

const definitions = {
    getUser : (id) => {
        return new Promise((resolve, reject) => {
            setTimeout(()=> {
                console.log('Getting User data...');
                resolve({id: id, userName: 'Shamik Roy'})
            }, 2000);
        })
    },
    getRepos : (user) => {
        return new Promise((resolve, reject) => {
            setTimeout(()=> {
                console.log('Getting repositories List...');
                resolve(['repo1', 'repo2']);
            }, 2000);
        });
    },
    getCommits: (repoId) => {
        return new Promise((resolve, reject) => {
            setTimeout(()=>{
                console.log('Getting commit List...');
                resolve([{ id: 1, commit: "First Commit"},{ id:2, commit: "Second Commit"}]);
            }, 2000);
        })
    }
module.exports = definitions;

// promise-consumer.js The following approach gives undefined in this line: console.log('Repository Data', repos); // promise-consumer.js 下面的方法在这一行给出了 undefined:console.log('Repository Data', repos);

const promise = require('./promise-definitions');
promise.getUser(10)
    .then((user)=> {
        console.log('User Data', user);
        promise.getRepos(user.userName);
    })
    .then((repos) => {
        console.log('Repository Data', repos);
        promise.getCommits(repos[0]);
    })
    .then(commits => {
        console.log('Commits', commits)
    })

However the follwing approach works fine:然而,以下方法工作正常:

const promise = require('./promise-definitions');
promise.getUser(10)
    .then((user)=> {
        console.log('User Data', user);
        return promise.getRepos(user.userName);
    })
    .then((repos) => {
        console.log('Repository Data', repos);
        return promise.getCommits(repos[0]);
    })
    .then(commits => {
        console.log('Commits', commits)
    })

Iam using a return statement when calling the individual promises and it is working fine.Can anyone please point out the reason for this.我在调用个人承诺时使用了 return 语句,它工作正常。任何人都可以指出原因。

Can anyone please point out the reason for this.谁能指出这个原因。

At the highest level, it's simply because this is how promise chains are designed to work.在最高级别,这仅仅是因为 promise 链的设计方式就是这样。 When you implement it the way they are designed to work, you get an expected result.当您按照设计的工作方式实施它时,您会得到预期的结果。 When you don't, you don't get the result you want.如果你不这样做,你就不会得到你想要的结果。

A .then() handler on a promise chain just calls its callback and looks at the return value. promise 链上的 .then .then()处理程序只是调用其回调并查看返回值。 If you supply a callback that returns nothing or returns a non-promise, then the promise chain just keeps right on going.如果您提供不返回任何内容或返回非承诺的回调,则 promise 链将继续运行。 The .then() infrastructure has NO idea at all what's going on inside the callback you supplied. .then()基础结构根本不知道您提供的回调内部发生了什么。 It has no magic powers to know you started some asynchronous operation inside your .then() handler that it should magically wait for.知道你在你的.then()处理程序中启动了一些异步操作,它应该神奇地等待它并没有什么魔力。 Instead, the ONLY way it knows to wait for something to finish is if you return a promise from the .then() handler.相反,它知道等待某事完成的唯一方法是,如果您从 .then .then()处理程序返回 promise。 This is how promises are designed.这就是 Promise 的设计方式。

In your first example, you call some function that returns a promise, but because you don't return the promise from the .then() handler, the parent promise chain does not know anything about your new promise. In your first example, you call some function that returns a promise, but because you don't return the promise from the .then .then() handler, the parent promise chain does not know anything about your new promise.

You have effectively just created a new branched promise chain that is not connected in any way to the original one.您实际上刚刚创建了一个新的分支 promise 链,该链未以任何方式连接到原始链。 This new promise chain proceeds on its own schedule and does not affect the original promise chain in any way.这个新的 promise 链按自己的时间表进行,不会以任何方式影响原始 promise 链。

In your second code block, you return the new promise from the .then() handler.在您的第二个代码块中,您从 .then .then()处理程序返回新的 promise。 That properly inserts that new promise into the existing promise chain and the parent promise chains waits for that newly returned promise to fulfill before proceeding with the rest of its chain. That properly inserts that new promise into the existing promise chain and the parent promise chains waits for that newly returned promise to fulfill before proceeding with the rest of its chain. This is, obviously, how you properly chain promises together.显然,这就是你如何正确地将 Promise 链接在一起的方式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM