Elffuss BraidHub

kikocis/lancedb public

4a63e77b7e97 · 24.3 KiBRawPermalink
1// Copyright 2023 Lance Developers.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use std::ops::Deref;
16
17use arrow_array::{RecordBatch, RecordBatchIterator};
18use lance::dataset::optimize::CompactionOptions;
19use lance::dataset::{ColumnAlteration, NewColumnTransform, WriteMode, WriteParams};
20use lancedb::table::{OptimizeAction, WriteOptions};
21
22use crate::arrow::{arrow_buffer_to_record_batch, record_batch_to_buffer};
23use lancedb::table::Table as LanceDbTable;
24use neon::prelude::*;
25use neon::types::buffer::TypedArray;
26
27use crate::error::ResultExt;
28use crate::{convert, runtime, JsDatabase};
29
30pub struct JsTable {
31 pub table: LanceDbTable,
32}
33
34impl Finalize for JsTable {}
35
36impl From<LanceDbTable> for JsTable {
37 fn from(table: LanceDbTable) -> Self {
38 Self { table }
39 }
40}
41
42impl JsTable {
43 pub(crate) fn js_create(mut cx: FunctionContext) -> JsResult<JsPromise> {
44 let db = cx
45 .this()
46 .downcast_or_throw::<JsBox<JsDatabase>, _>(&mut cx)?;
47 let table_name = cx.argument::<JsString>(0)?.value(&mut cx);
48 let buffer = cx.argument::<JsBuffer>(1)?;
49 let (batches, schema) =
50 arrow_buffer_to_record_batch(buffer.as_slice(&cx)).or_throw(&mut cx)?;
51
52 // Write mode
53 let mode = match cx.argument::<JsString>(2)?.value(&mut cx).as_str() {
54 "overwrite" => WriteMode::Overwrite,
55 "append" => WriteMode::Append,
56 "create" => WriteMode::Create,
57 _ => {
58 return cx.throw_error("Table::create only supports 'overwrite' and 'create' modes")
59 }
60 };
61 let params = WriteParams {
62 mode,
63 ..WriteParams::default()
64 };
65
66 let rt = runtime(&mut cx)?;
67 let channel = cx.channel();
68
69 let (deferred, promise) = cx.promise();
70 let database = db.database.clone();
71
72 rt.spawn(async move {
73 let batch_reader = RecordBatchIterator::new(batches.into_iter().map(Ok), schema);
74 let table_rst = database
75 .create_table(&table_name, batch_reader)
76 .write_options(WriteOptions {
77 lance_write_params: Some(params),
78 })
79 .execute()
80 .await;
81
82 deferred.settle_with(&channel, move |mut cx| {
83 let table = table_rst.or_throw(&mut cx)?;
84 Ok(cx.boxed(Self::from(table)))
85 });
86 });
87 Ok(promise)
88 }
89
90 pub(crate) fn js_add(mut cx: FunctionContext) -> JsResult<JsPromise> {
91 let js_table = cx.this().downcast_or_throw::<JsBox<Self>, _>(&mut cx)?;
92 let buffer = cx.argument::<JsBuffer>(0)?;
93 let write_mode = cx.argument::<JsString>(1)?.value(&mut cx);
94 let (batches, schema) =
95 arrow_buffer_to_record_batch(buffer.as_slice(&cx)).or_throw(&mut cx)?;
96 let rt = runtime(&mut cx)?;
97 let channel = cx.channel();
98 let table = js_table.table.clone();
99
100 let (deferred, promise) = cx.promise();
101 let write_mode = match write_mode.as_str() {
102 "create" => WriteMode::Create,
103 "append" => WriteMode::Append,
104 "overwrite" => WriteMode::Overwrite,
105 s => return cx.throw_error(format!("invalid write mode {}", s)),
106 };
107
108 let params = WriteParams {
109 mode: write_mode,
110 ..WriteParams::default()
111 };
112
113 rt.spawn(async move {
114 let batch_reader = RecordBatchIterator::new(batches.into_iter().map(Ok), schema);
115 let add_result = table
116 .add(batch_reader)
117 .write_options(WriteOptions {
118 lance_write_params: Some(params),
119 })
120 .execute()
121 .await;
122
123 deferred.settle_with(&channel, move |mut cx| {
124 add_result.or_throw(&mut cx)?;
125 Ok(cx.boxed(Self::from(table)))
126 });
127 });
128 Ok(promise)
129 }
130
131 pub(crate) fn js_count_rows(mut cx: FunctionContext) -> JsResult<JsPromise> {
132 let js_table = cx.this().downcast_or_throw::<JsBox<Self>, _>(&mut cx)?;
133 let filter = cx
134 .argument_opt(0)
135 .and_then(|filt| {
136 if filt.is_a::<JsUndefined, _>(&mut cx) || filt.is_a::<JsNull, _>(&mut cx) {
137 None
138 } else {
139 Some(
140 filt.downcast_or_throw::<JsString, _>(&mut cx)
141 .map(|js_filt| js_filt.deref().value(&mut cx)),
142 )
143 }
144 })
145 .transpose()?;
146 let rt = runtime(&mut cx)?;
147 let (deferred, promise) = cx.promise();
148 let channel = cx.channel();
149 let table = js_table.table.clone();
150
151 rt.spawn(async move {
152 let num_rows_result = table.count_rows(filter).await;
153
154 deferred.settle_with(&channel, move |mut cx| {
155 let num_rows = num_rows_result.or_throw(&mut cx)?;
156 Ok(cx.number(num_rows as f64))
157 });
158 });
159 Ok(promise)
160 }
161
162 pub(crate) fn js_delete(mut cx: FunctionContext) -> JsResult<JsPromise> {
163 let js_table = cx.this().downcast_or_throw::<JsBox<Self>, _>(&mut cx)?;
164 let rt = runtime(&mut cx)?;
165 let (deferred, promise) = cx.promise();
166 let predicate = cx.argument::<JsString>(0)?.value(&mut cx);
167 let channel = cx.channel();
168 let table = js_table.table.clone();
169
170 rt.spawn(async move {
171 let delete_result = table.delete(&predicate).await;
172
173 deferred.settle_with(&channel, move |mut cx| {
174 delete_result.or_throw(&mut cx)?;
175 Ok(cx.boxed(Self::from(table)))
176 })
177 });
178 Ok(promise)
179 }
180
181 pub(crate) fn js_merge_insert(mut cx: FunctionContext) -> JsResult<JsPromise> {
182 let js_table = cx.this().downcast_or_throw::<JsBox<Self>, _>(&mut cx)?;
183 let rt = runtime(&mut cx)?;
184 let (deferred, promise) = cx.promise();
185 let channel = cx.channel();
186 let table = js_table.table.clone();
187
188 let key = cx.argument::<JsString>(0)?.value(&mut cx);
189 let mut builder = table.merge_insert(&[&key]);
190 if cx.argument::<JsBoolean>(1)?.value(&mut cx) {
191 let filter = cx.argument_opt(2).unwrap();
192 if filter.is_a::<JsNull, _>(&mut cx) {
193 builder.when_matched_update_all(None);
194 } else {
195 let filter = filter
196 .downcast_or_throw::<JsString, _>(&mut cx)?
197 .deref()
198 .value(&mut cx);
199 builder.when_matched_update_all(Some(filter));
200 }
201 }
202 if cx.argument::<JsBoolean>(3)?.value(&mut cx) {
203 builder.when_not_matched_insert_all();
204 }
205 if cx.argument::<JsBoolean>(4)?.value(&mut cx) {
206 let filter = cx.argument_opt(5).unwrap();
207 if filter.is_a::<JsNull, _>(&mut cx) {
208 builder.when_not_matched_by_source_delete(None);
209 } else {
210 let filter = filter
211 .downcast_or_throw::<JsString, _>(&mut cx)?
212 .deref()
213 .value(&mut cx);
214 builder.when_not_matched_by_source_delete(Some(filter));
215 }
216 }
217
218 let buffer = cx.argument::<JsBuffer>(6)?;
219 let (batches, schema) =
220 arrow_buffer_to_record_batch(buffer.as_slice(&cx)).or_throw(&mut cx)?;
221
222 rt.spawn(async move {
223 let new_data = RecordBatchIterator::new(batches.into_iter().map(Ok), schema);
224 let merge_insert_result = builder.execute(Box::new(new_data)).await;
225
226 deferred.settle_with(&channel, move |mut cx| {
227 merge_insert_result.or_throw(&mut cx)?;
228 Ok(cx.boxed(Self::from(table)))
229 })
230 });
231 Ok(promise)
232 }
233
234 pub(crate) fn js_update(mut cx: FunctionContext) -> JsResult<JsPromise> {
235 let js_table = cx.this().downcast_or_throw::<JsBox<Self>, _>(&mut cx)?;
236 let table = js_table.table.clone();
237
238 let rt = runtime(&mut cx)?;
239 let (deferred, promise) = cx.promise();
240 let channel = cx.channel();
241
242 // create a vector of updates from the passed map
243 let updates_arg = cx.argument::<JsObject>(1)?;
244 let properties = updates_arg.get_own_property_names(&mut cx)?;
245 let mut updates: Vec<(String, String)> =
246 Vec::with_capacity(properties.len(&mut cx) as usize);
247
248 let len_properties = properties.len(&mut cx);
249 for i in 0..len_properties {
250 let property = properties
251 .get_value(&mut cx, i)?
252 .downcast_or_throw::<JsString, _>(&mut cx)?;
253
254 let value = updates_arg
255 .get_value(&mut cx, property)?
256 .downcast_or_throw::<JsString, _>(&mut cx)?;
257
258 let property = property.value(&mut cx);
259 let value = value.value(&mut cx);
260 updates.push((property, value));
261 }
262
263 // get the filter/predicate if the user passed one
264 let predicate = cx.argument_opt(0);
265 let predicate = predicate.unwrap().downcast::<JsString, _>(&mut cx);
266 let predicate = match predicate {
267 Ok(_) => {
268 let val = predicate.map(|s| s.value(&mut cx)).unwrap();
269 Some(val)
270 }
271 Err(_) => {
272 // if the predicate is not string, check it's null otherwise an invalid
273 // type was passed
274 cx.argument::<JsNull>(0)?;
275 None
276 }
277 };
278
279 rt.spawn(async move {
280 let updates_arg = updates
281 .iter()
282 .map(|(k, v)| (k.as_str(), v.as_str()))
283 .collect::<Vec<_>>();
284
285 let predicate = predicate.as_deref();
286
287 let mut update_op = table.update();
288 if let Some(predicate) = predicate {
289 update_op = update_op.only_if(predicate);
290 }
291 for (column, value) in updates_arg {
292 update_op = update_op.column(column, value);
293 }
294 let update_result = update_op.execute().await;
295 deferred.settle_with(&channel, move |mut cx| {
296 update_result.or_throw(&mut cx)?;
297 Ok(cx.boxed(Self::from(table)))
298 })
299 });
300
301 Ok(promise)
302 }
303
304 pub(crate) fn js_cleanup(mut cx: FunctionContext) -> JsResult<JsPromise> {
305 let js_table = cx.this().downcast_or_throw::<JsBox<Self>, _>(&mut cx)?;
306 let rt = runtime(&mut cx)?;
307 let (deferred, promise) = cx.promise();
308 let table = js_table.table.clone();
309 let channel = cx.channel();
310
311 let older_than: i64 = cx
312 .argument_opt(0)
313 .and_then(|val| val.downcast::<JsNumber, _>(&mut cx).ok())
314 .map(|val| val.value(&mut cx) as i64)
315 .unwrap_or_else(|| 2 * 7 * 24 * 60); // 2 weeks
316 let older_than = chrono::Duration::try_minutes(older_than).unwrap();
317 let delete_unverified: Option<bool> = Some(
318 cx.argument_opt(1)
319 .and_then(|val| val.downcast::<JsBoolean, _>(&mut cx).ok())
320 .map(|val| val.value(&mut cx))
321 .unwrap_or_default(),
322 );
323 let error_if_tagged_old_versions: Option<bool> = Some(
324 cx.argument_opt(2)
325 .and_then(|val| val.downcast::<JsBoolean, _>(&mut cx).ok())
326 .map(|val| val.value(&mut cx))
327 .unwrap_or_default(),
328 );
329
330 rt.spawn(async move {
331 let stats = table
332 .optimize(OptimizeAction::Prune {
333 older_than: Some(older_than),
334 delete_unverified,
335 error_if_tagged_old_versions,
336 })
337 .await;
338
339 deferred.settle_with(&channel, move |mut cx| {
340 let stats = stats.or_throw(&mut cx)?;
341
342 let prune_stats = stats.prune.as_ref().expect("Prune stats missing");
343 let output_metrics = JsObject::new(&mut cx);
344 let bytes_removed = cx.number(prune_stats.bytes_removed as f64);
345 output_metrics.set(&mut cx, "bytesRemoved", bytes_removed)?;
346
347 let old_versions = cx.number(prune_stats.old_versions as f64);
348 output_metrics.set(&mut cx, "oldVersions", old_versions)?;
349
350 let output_table = cx.boxed(Self::from(table));
351
352 let output = JsObject::new(&mut cx);
353 output.set(&mut cx, "metrics", output_metrics)?;
354 output.set(&mut cx, "newTable", output_table)?;
355
356 Ok(output)
357 })
358 });
359 Ok(promise)
360 }
361
362 pub(crate) fn js_compact(mut cx: FunctionContext) -> JsResult<JsPromise> {
363 let js_table = cx.this().downcast_or_throw::<JsBox<Self>, _>(&mut cx)?;
364 let rt = runtime(&mut cx)?;
365 let (deferred, promise) = cx.promise();
366 let table = js_table.table.clone();
367 let channel = cx.channel();
368
369 let js_options = cx.argument::<JsObject>(0)?;
370 let mut options = CompactionOptions::default();
371
372 if let Some(target_rows) =
373 js_options.get_opt::<JsNumber, _, _>(&mut cx, "targetRowsPerFragment")?
374 {
375 options.target_rows_per_fragment = target_rows.value(&mut cx) as usize;
376 }
377 if let Some(max_per_group) =
378 js_options.get_opt::<JsNumber, _, _>(&mut cx, "maxRowsPerGroup")?
379 {
380 options.max_rows_per_group = max_per_group.value(&mut cx) as usize;
381 }
382 if let Some(materialize_deletions) =
383 js_options.get_opt::<JsBoolean, _, _>(&mut cx, "materializeDeletions")?
384 {
385 options.materialize_deletions = materialize_deletions.value(&mut cx);
386 }
387 if let Some(materialize_deletions_threshold) =
388 js_options.get_opt::<JsNumber, _, _>(&mut cx, "materializeDeletionsThreshold")?
389 {
390 options.materialize_deletions_threshold =
391 materialize_deletions_threshold.value(&mut cx) as f32;
392 }
393 if let Some(num_threads) = js_options.get_opt::<JsNumber, _, _>(&mut cx, "numThreads")? {
394 options.num_threads = Some(num_threads.value(&mut cx) as usize);
395 }
396
397 rt.spawn(async move {
398 let stats = table
399 .optimize(OptimizeAction::Compact {
400 options,
401 remap_options: None,
402 })
403 .await;
404
405 deferred.settle_with(&channel, move |mut cx| {
406 let stats = stats.or_throw(&mut cx)?;
407 let stats = stats.compaction.as_ref().expect("Compact stats missing");
408
409 let output_metrics = JsObject::new(&mut cx);
410 let fragments_removed = cx.number(stats.fragments_removed as f64);
411 output_metrics.set(&mut cx, "fragmentsRemoved", fragments_removed)?;
412
413 let fragments_added = cx.number(stats.fragments_added as f64);
414 output_metrics.set(&mut cx, "fragmentsAdded", fragments_added)?;
415
416 let files_removed = cx.number(stats.files_removed as f64);
417 output_metrics.set(&mut cx, "filesRemoved", files_removed)?;
418
419 let files_added = cx.number(stats.files_added as f64);
420 output_metrics.set(&mut cx, "filesAdded", files_added)?;
421
422 let output_table = cx.boxed(Self::from(table));
423
424 let output = JsObject::new(&mut cx);
425 output.set(&mut cx, "metrics", output_metrics)?;
426 output.set(&mut cx, "newTable", output_table)?;
427
428 Ok(output)
429 })
430 });
431 Ok(promise)
432 }
433
434 pub(crate) fn js_list_indices(mut cx: FunctionContext) -> JsResult<JsPromise> {
435 let js_table = cx.this().downcast_or_throw::<JsBox<Self>, _>(&mut cx)?;
436 let rt = runtime(&mut cx)?;
437 let (deferred, promise) = cx.promise();
438 // let predicate = cx.argument::<JsString>(0)?.value(&mut cx);
439 let channel = cx.channel();
440 let table = js_table.table.clone();
441
442 rt.spawn(async move {
443 let indices = table.as_native().unwrap().load_indices().await;
444
445 deferred.settle_with(&channel, move |mut cx| {
446 let indices = indices.or_throw(&mut cx)?;
447
448 let output = JsArray::new(&mut cx, indices.len() as u32);
449 for (i, index) in indices.iter().enumerate() {
450 let js_index = JsObject::new(&mut cx);
451 let index_name = cx.string(index.index_name.clone());
452 js_index.set(&mut cx, "name", index_name)?;
453
454 let index_uuid = cx.string(index.index_uuid.clone());
455 js_index.set(&mut cx, "uuid", index_uuid)?;
456
457 let js_index_columns = JsArray::new(&mut cx, index.columns.len() as u32);
458 for (j, column) in index.columns.iter().enumerate() {
459 let js_column = cx.string(column.clone());
460 js_index_columns.set(&mut cx, j as u32, js_column)?;
461 }
462 js_index.set(&mut cx, "columns", js_index_columns)?;
463
464 output.set(&mut cx, i as u32, js_index)?;
465 }
466
467 Ok(output)
468 })
469 });
470 Ok(promise)
471 }
472
473 #[allow(deprecated)]
474 pub(crate) fn js_index_stats(mut cx: FunctionContext) -> JsResult<JsPromise> {
475 let js_table = cx.this().downcast_or_throw::<JsBox<Self>, _>(&mut cx)?;
476 let rt = runtime(&mut cx)?;
477 let (deferred, promise) = cx.promise();
478 let index_uuid = cx.argument::<JsString>(0)?.value(&mut cx);
479 let channel = cx.channel();
480 let table = js_table.table.clone();
481
482 rt.spawn(async move {
483 let load_stats = futures::try_join!(
484 table.as_native().unwrap().count_indexed_rows(&index_uuid),
485 table.as_native().unwrap().count_unindexed_rows(&index_uuid)
486 );
487
488 deferred.settle_with(&channel, move |mut cx| {
489 let (indexed_rows, unindexed_rows) = load_stats.or_throw(&mut cx)?;
490
491 let output = JsObject::new(&mut cx);
492
493 match indexed_rows {
494 Some(x) => {
495 let i = cx.number(x as f64);
496 output.set(&mut cx, "numIndexedRows", i)?;
497 }
498 None => {
499 let null = cx.null();
500 output.set(&mut cx, "numIndexedRows", null)?;
501 }
502 };
503
504 match unindexed_rows {
505 Some(x) => {
506 let i = cx.number(x as f64);
507 output.set(&mut cx, "numUnindexedRows", i)?;
508 }
509 None => {
510 let null = cx.null();
511 output.set(&mut cx, "numUnindexedRows", null)?;
512 }
513 };
514
515 Ok(output)
516 })
517 });
518
519 Ok(promise)
520 }
521
522 pub(crate) fn js_schema(mut cx: FunctionContext) -> JsResult<JsPromise> {
523 let js_table = cx.this().downcast_or_throw::<JsBox<Self>, _>(&mut cx)?;
524 let rt = runtime(&mut cx)?;
525 let (deferred, promise) = cx.promise();
526 let channel = cx.channel();
527 let table = js_table.table.clone();
528
529 let is_electron = cx
530 .argument::<JsBoolean>(0)
531 .or_throw(&mut cx)?
532 .value(&mut cx);
533
534 rt.spawn(async move {
535 let schema = table.schema().await;
536 deferred.settle_with(&channel, move |mut cx| {
537 let schema = schema.or_throw(&mut cx)?;
538 let batches = vec![RecordBatch::new_empty(schema)];
539 let buffer = record_batch_to_buffer(batches).or_throw(&mut cx)?;
540 convert::new_js_buffer(buffer, &mut cx, is_electron)
541 })
542 });
543 Ok(promise)
544 }
545
546 pub(crate) fn js_add_columns(mut cx: FunctionContext) -> JsResult<JsPromise> {
547 let expressions = cx
548 .argument::<JsArray>(0)?
549 .to_vec(&mut cx)?
550 .into_iter()
551 .map(|val| {
552 let obj = val.downcast_or_throw::<JsObject, _>(&mut cx)?;
553 let name = obj.get::<JsString, _, _>(&mut cx, "name")?.value(&mut cx);
554 let sql = obj
555 .get::<JsString, _, _>(&mut cx, "valueSql")?
556 .value(&mut cx);
557 Ok((name, sql))
558 })
559 .collect::<NeonResult<Vec<(String, String)>>>()?;
560
561 let transforms = NewColumnTransform::SqlExpressions(expressions);
562
563 let js_table = cx.this().downcast_or_throw::<JsBox<Self>, _>(&mut cx)?;
564 let rt = runtime(&mut cx)?;
565
566 let (deferred, promise) = cx.promise();
567 let channel = cx.channel();
568 let table = js_table.table.clone();
569
570 rt.spawn(async move {
571 let result = table.add_columns(transforms, None).await;
572 deferred.settle_with(&channel, move |mut cx| {
573 result.or_throw(&mut cx)?;
574 Ok(cx.undefined())
575 })
576 });
577
578 Ok(promise)
579 }
580
581 pub(crate) fn js_alter_columns(mut cx: FunctionContext) -> JsResult<JsPromise> {
582 let alterations = cx
583 .argument::<JsArray>(0)?
584 .to_vec(&mut cx)?
585 .into_iter()
586 .map(|val| {
587 let obj = val.downcast_or_throw::<JsObject, _>(&mut cx)?;
588 let path = obj.get::<JsString, _, _>(&mut cx, "path")?.value(&mut cx);
589 let rename = obj
590 .get_opt::<JsString, _, _>(&mut cx, "rename")?
591 .map(|val| val.value(&mut cx));
592 let nullable = obj
593 .get_opt::<JsBoolean, _, _>(&mut cx, "nullable")?
594 .map(|val| val.value(&mut cx));
595 // TODO: support data type here. Will need to do some serialization/deserialization
596
597 if rename.is_none() && nullable.is_none() {
598 return cx.throw_error("At least one of 'name' or 'nullable' must be provided");
599 }
600
601 Ok(ColumnAlteration {
602 path,
603 rename,
604 nullable,
605 // TODO: wire up this field
606 data_type: None,
607 })
608 })
609 .collect::<NeonResult<Vec<ColumnAlteration>>>()?;
610
611 let js_table = cx.this().downcast_or_throw::<JsBox<Self>, _>(&mut cx)?;
612 let rt = runtime(&mut cx)?;
613
614 let (deferred, promise) = cx.promise();
615 let channel = cx.channel();
616 let table = js_table.table.clone();
617
618 rt.spawn(async move {
619 let result = table.alter_columns(&alterations).await;
620 deferred.settle_with(&channel, move |mut cx| {
621 result.or_throw(&mut cx)?;
622 Ok(cx.undefined())
623 })
624 });
625
626 Ok(promise)
627 }
628
629 pub(crate) fn js_drop_columns(mut cx: FunctionContext) -> JsResult<JsPromise> {
630 let columns = cx
631 .argument::<JsArray>(0)?
632 .to_vec(&mut cx)?
633 .into_iter()
634 .map(|val| {
635 Ok(val
636 .downcast_or_throw::<JsString, _>(&mut cx)?
637 .value(&mut cx))
638 })
639 .collect::<NeonResult<Vec<String>>>()?;
640
641 let js_table = cx.this().downcast_or_throw::<JsBox<Self>, _>(&mut cx)?;
642 let rt = runtime(&mut cx)?;
643
644 let (deferred, promise) = cx.promise();
645 let channel = cx.channel();
646 let table = js_table.table.clone();
647
648 rt.spawn(async move {
649 let col_refs = columns.iter().map(|s| s.as_str()).collect::<Vec<_>>();
650 let result = table.drop_columns(&col_refs).await;
651 deferred.settle_with(&channel, move |mut cx| {
652 result.or_throw(&mut cx)?;
653 Ok(cx.undefined())
654 })
655 });
656
657 Ok(promise)
658 }
659}