问题描述
我编写了一个库函数pRead(Path)
,它返回一个JavaScript Promise 以使用Ajax 在Apache 服务器下读取本地计算机上的文件.我不会包含这方面的代码,因为它使用了标准技术,任何人都可以很好地回答这个问题.
I have written a library function pRead(Path)
, which returns a JavaScript Promise to read a file on the local computer under an Apache server, using Ajax. I won't include the code for this, as it uses standard technology that is well-known to anyone who can give a good answer to this question.
我想编写第二个库函数 pReadObj(Path)
,它将返回一个 Promise 以读取 JSON 文件并将其对象值提供给异步代码.它应该像这样工作:
I want to write a second library function, pReadObj(Path)
, which will return a Promise to read a JSON file and provide its object value to asynchronous code. It should work like this:
pReadObj("test.json").then(then2).catch(pErr);
function then2(obj)
{
alert(JSON.stringify(obj)); // Shows the JSON obj
} // then2
这是我写的代码:
var globalPreviousResolve;
function pReadObj(Path) // Promise to read JSON from file
{
return new Promise(function(resolve,reject)
{
globalPreviousResolve=resolve;
pRead(Path).then(pReadObj2).catch(pErr);
});
} // pReadObj
function pReadObj2(JSONStr)
{
globalPreviousResolve(JSON.parse(JSONStr));
} // pReadObj2
function pTestDB() // Called from button
{
pReadObj("test.json").then(then2).catch(pErr);
} // pTestDB
这可行,但有一个问题:使用全局变量来保存解析回调不仅丑陋,而且如果在短时间内两次调用 pReadObj 并且磁盘读取需要更长的时间,它显然会出现故障
This works, but has a problem: using a global variable to hold the resolve callback is not only ugly, but it will clearly malfunction if two calls to pReadObj happen within a short period of time and the disk read takes a longer time than that.
我在想,resolve 函数需要以某种方式存储在 Promise 中.
The resolve function needs to be stored inside the Promise in some way, I'm thinking.
推荐答案
无需显式创建 Promise;只需返回由 创建的那个.然后
:
There's no need to explicitly create a Promise; just return the one created by .then
:
function pReadObj(Path) {
return pRead(Path).then(JSON.parse);
}
这篇关于嵌套(扩展)承诺似乎需要一个全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!