Stay Hungry,Stay Foolish!

JS两种同步写异步的方法

async/await

https://javascript.info/async-await

需要浏览器支持,后者使用webpack转换为ES5.

There’s a special syntax to work with promises in a more comfortable fashion, called “async/await”. It’s surprisingly easy to understand and use.

Async functions

Let’s start with the async keyword. It can be placed before a function, like this:

async function f() {
  return 1;
}
async
function
f
(
)
{
return
1
;
}

The word “async” before a function means one simple thing: a function always returns a promise. Other values are wrapped in a resolved promise automatically.

For instance, this function returns a resolved promise with the result of 1; let’s test it:

 
async function f() {
  return 1;
}

f().then(alert); // 1
async
function
f
(
)
{
return
1
;
}
f
(
)
.
then
(
)
;
// 1

…We could explicitly return a promise, which would be the same:

 
async function f() {
  return Promise.resolve(1);
}

f().then(alert); // 1
async
function
f
(
)
{
return
.
resolve
(
1
)
;
}
f
(
)
.
then
(
)
;
// 1

So, async ensures that the function returns a promise, and wraps non-promises in it. Simple enough, right? But not only that. There’s another keyword, await, that works only inside async functions, and it’s pretty cool.

 

Bluebirds-coroutine

http://bluebirdjs.com/docs/api/promise.coroutine.html

具有跨浏览器支持性,不需要使用webpack进行翻译。

实际上Node环境也支持。

Promise.coroutine(GeneratorFunction(...arguments) generatorFunction, Object options) -> function

Returns a function that can use yield to yield promises. Control is returned back to the generator when the yielded promise settles. This can lead to less verbose code when doing lots of sequential async calls with minimal processing in between. Requires node.js 0.12+, io.js 1.0+ or Google Chrome 40+.

var Promise = require("bluebird");

function PingPong() {

}

PingPong.prototype.ping = Promise.coroutine(function* (val) {
    console.log("Ping?", val);
    yield Promise.delay(500);
    this.pong(val+1);
});

PingPong.prototype.pong = Promise.coroutine(function* (val) {
    console.log("Pong!", val);
    yield Promise.delay(500);
    this.ping(val+1);
});

var a = new PingPong();
a.ping(0);

Running the example:

$ node test.js
Ping? 0
Pong! 1
Ping? 2
Pong! 3
Ping? 4
Pong! 5
Ping? 6
Pong! 7
Ping? 8
...

 

posted @   lightsong  阅读(1793)  评论(0编辑  收藏  举报
编辑推荐:
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· [.NET]调用本地 Deepseek 模型
阅读排行:
· 全网最简单!3分钟用满血DeepSeek R1开发一款AI智能客服,零代码轻松接入微信、公众号、小程
· .NET 10 首个预览版发布,跨平台开发与性能全面提升
· 《HelloGitHub》第 107 期
· 全程使用 AI 从 0 到 1 写了个小工具
· 从文本到图像:SSE 如何助力 AI 内容实时呈现?(Typescript篇)
千山鸟飞绝,万径人踪灭
点击右上角即可分享
微信分享提示