简体   繁体   English

Promise.resolve()和resolve()之间的区别?

[英]Difference between Promise.resolve() and just resolve()?

I wrote the code below: 我写了下面的代码:

function readFile(path) {
    return new Promise(function(resolve, reject){
        if(!fs.existsSync(path))
            return reject(new Error("data.json file does not exist"));
        else {
            console.log("File is actually found!");
            return Promise.resolve("File found");
        }
    })
}

readFile(path)
    .then(value => {
        console.log(value);
    })
    .catch(err => {
        console.log(err);
    })

What happens: 怎么了:
If the file exists, the console output is just File is actually found! 如果文件存在,控制台输出只是File is actually found! If the file does not exist, it displays: data.json file does not exist along with the error stack. 如果该文件不存在,则显示: data.json file does not exist与错误堆栈一起data.json file does not exist

What I want: 我想要的是:
When the file does exist, I want File found to be displayed in addition to File is actually found! 当文件不存在,我想File found显示在除了File is actually found! . I found that this happens when I replace return Promise.resolve("File found"); 我发现当我替换return Promise.resolve("File found");时会发生这种情况return Promise.resolve("File found"); with just resolve("File found"); 只需resolve("File found"); or even return resolve("File found"); 甚至return resolve("File found"); .

Question: 题:
What really is the difference between resolve() and Promise.resolve() ? resolve()Promise.resolve()之间有什么区别? Why does returning or not returning not make a difference (I guess it is because it is the last statement in the function). 为什么返回或不返回没有区别(我想这是因为它是函数中的最后一个语句)。

Note: I use existsSync() because I want the process to be blocking until the file is actually read, because if the file is not read, then there is nothing to be done! 注意:我使用existsSync()因为我希望在实际读取文件之前阻塞进程,因为如果没有读取文件,那么就没有什么existsSync() I understand promise might not be needed here, but I still use it because that is what I am trying to learn. 我理解这里可能不需要承诺,但我仍然使用它,因为这是我想要学习的东西。

Thanks! 谢谢!

Edit: One more question - what actually should be rejected and resolved? 编辑:还有一个问题 - 究竟应该拒绝和解决什么? I mean, in the code above, I pass new Error(...) to reject() and a string to resolve() - is that alright? 我的意思是,在上面的代码中,我将new Error(...)传递给reject()和一个字符串来resolve() - 这没关系吗?

Promise.resolve wraps an expression in a Promise. Promise.resolve在Promise中包装表达式。 So Promise.resolve("File found"); 所以Promise.resolve("File found"); is 'File found' wrapped in a Promise that resolves immediately. 'File found'包含在一个立即解决的承诺中。

Look at where the wrapped Promise is going in this code - you're returning it to the caller of the new Promise constructor. 查看包装的Promise在此代码中的位置 - 您将其返回给new Promise构造函数的调用者。 But the Promise constructor completely ignores a return value, if any. 但Promise构造函数完全忽略了返回值(如果有的话)。 It's kind of like returning something when iterating in forEach - it just gets ignored. 这有点像在forEach迭代时返回一些东西 - 它只是被忽略了。

In order to resolve a Promise constructed via the Promise constructor, you must call the first argument provided to the callback (which is conventionally named resolve , but may be named anything you want). 为了解析通过Promise构造函数构造的Promise, 必须调用提供给回调的第一个参数(通常命名为resolve ,但可以命名为任何你想要的名称)。

Also note that there's no need at all to wrap the rejection in new Error - if you just have a string message to send to the consumer, it's fine to reject with just a string. 另请注意,根本不需要将拒绝包装在new Error - 如果您只是要将一个字符串消息发送给消费者,那么只需要一个字符串就可以拒绝。

function readFile(path) {
    return new Promise(function(resolve, reject){
        if(!fs.existsSync(path))
            reject("data.json file does not exist");
        else {
            console.log("File is actually found!");
            resolve("File found");
        }
    })
}

Which is equivalent to: 这相当于:

function readFile(path) {
    return new Promise((fnToCallToResolveConstructedPromise, fnToCallToRejectConstructedPromise) => {
        if(!fs.existsSync(path))
            fnToCallToRejectConstructedPromise("data.json file does not exist");
        else {
            console.log("File is actually found!");
            fnToCallToResolveConstructedPromise("File found");
        }
    })
}

You can wrap it in an error object if it provides useful info for you, aside from the string describing the error, but otherwise, best to omit it, and just call reject with a string. 如果它为您提供有用的信息,除了描述错误的字符串之外,您可以将其包装在错误对象中,但除此之外,最好省略它,并且只需使用字符串调用reject

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

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