你可以使用 Promises 使任何东西“异步”:
function asyncStringify(str) {
return new Promise((resolve, reject) => {
resolve(JSON.stringify(str));
});
}
Run Code Online (Sandbox Code Playgroud)
然后你可以像任何其他承诺一样使用它:
asyncStringfy(str).then(ajaxSubmit);
Run Code Online (Sandbox Code Playgroud)
请注意,因为代码不是异步的,promise 将被立即解析(字符串化 JSON 没有阻塞操作,它不需要任何系统调用)。
如果您的平台支持,您还可以使用 async/await API:
async function asyncStringify(str) {
return JSON.stringify(str);
}
Run Code Online (Sandbox Code Playgroud)
然后你可以用同样的方式使用它:
asyncStringfy(str).then(ajaxSubmit);
// or use the "await" API
const strJson = await asyncStringify(str);
ajaxSubmit(strJson);
Run Code Online (Sandbox Code Playgroud)
编辑:添加真正的异步解析/字符串化(可能是因为我们解析的东西太复杂)的一种方法是将作业传递给另一个进程(或服务)并等待响应。
您可以通过多种方式执行此操作(例如创建共享 REST API 的新服务),我将在此处演示一种通过进程之间的消息传递来执行此操作的方法:
首先创建一个文件来处理解析/字符串化。为了示例,将其称为 async-json.js:
// async-json.js
function stringify(value) {
return JSON.stringify(value);
}
function parse(value) {
return JSON.parse(value);
}
process.on('message', function(message) {
let result;
if (message.method === 'stringify') {
result = stringify(message.value)
} else if (message.method === 'parse') {
result = parse(message.value);
}
process.send({ callerId: message.callerId, returnValue: result });
});
Run Code Online (Sandbox Code Playgroud)
这个过程所做的就是等待一条消息,要求对 JSON 进行字符串化或解析,然后以正确的值进行响应。现在,在您的代码上,您可以分叉此脚本并来回发送消息。每当发送请求时,您都会创建一个新的承诺,每当响应返回该请求时,您就可以解析承诺:
const fork = require('child_process').fork;
const asyncJson = fork(__dirname + '/async-json.js');
const callers = {};
asyncJson.on('message', function(response) {
callers[response.callerId].resolve(response.returnValue);
});
function callAsyncJson(method, value) {
const callerId = parseInt(Math.random() * 1000000);
const callPromise = new Promise((resolve, reject) => {
callers[callerId] = { resolve: resolve, reject: reject };
asyncJson.send({ callerId: callerId, method: method, value: value });
});
return callPromise;
}
function JsonStringify(value) {
return callAsyncJson('stringify', value);
}
function JsonParse(value) {
return callAsyncJson('parse', value);
}
JsonStringify({ a: 1 }).then(console.log.bind(console));
JsonParse('{ "a": "1" }').then(console.log.bind(console));
Run Code Online (Sandbox Code Playgroud)
注意:这只是一个例子,但是知道了这一点,您可以找出其他改进或其他方法来做到这一点。希望这是有帮助的。
看看这个,另一个npm包 -
async-json 是一个提供标准 JSON.stringify 异步版本的库。
安装-
npm install async-json
Run Code Online (Sandbox Code Playgroud)
例子-
var asyncJSON = require('async-json');
asyncJSON.stringify({ some: "data" }, function (err, jsonValue) {
if (err) {
throw err;
}
jsonValue === '{"some":"data"}';
});
Run Code Online (Sandbox Code Playgroud)
注意-没有测试它,您需要手动检查它的依赖关系和所需的包。
| 归档时间: |
|
| 查看次数: |
5091 次 |
| 最近记录: |