-
Notifications
You must be signed in to change notification settings - Fork 0
/
promise.as
66 lines (55 loc) · 1.56 KB
/
promise.as
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
const Promise = make_ability('Promise')
const make_promise = (resolver) => {
const this = { ok_cbs: [], err_cbs: [], res:null, state: 'pending' }
resolver((res) => {
this.res = res
this.state = 'ok'
this.ok_cbs.select(fn => fn(res))
}, (errmsg) => {
this.state = 'err'
this.err_cbs.select(fn => fn(res))
})
use_ability(this, Promise)
}
define_member_function(Promise, {
then: (this, cb) => {
((this.state) == 'ok') ? @{
make_promise((resolve) => resolve(cb(this.res)))
} : @{
make_promise((resolve) => {
this.ok_cbs.push(res => {
resolve(cb(res))
})
})
}
}
})
const fetch_as_promsie = (url, params = { method: 'get' }) => {
make_promise((resolve, err) => {
fetch_async(url, params, resolve)
})
}
@{
const global = mem()
const _sync_fetch = fetch
global.fetch = fetch_as_promsie
global.fetch_sync = _sync_fetch
}
/*
const dd = () => make_promise(cb => cb('1'),null).then(() => log(2)).then(() => log(3))
micro(dd)
const ddc = () => make_promise(cb => macro(() => cb('xxxx')),null).then((x) => log(x, 21)).then(() => log(31))
micro(ddc)
const dc = () => fetch('https://github.com/orgs/xiachufang/dashboard',{ method: 'get' } ).then(data => {
log(json.stringify(data))
fs.write('dashboard.html', data.data)
})
micro(dc)
const call_api_promise = (path) => {
const url = 'https://api.ioflow.link'+path
fetch(url, { method: 'get' })
}
const p = call_api_promise('/message').then(v => v.data)
p.then(_ => log('twice callback'))
p.then(v => log(v, 23333))
*/